﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Windows.Forms;

namespace WenSkin;

public static class DL
{

    public static string GetVersionString()
    {
        return $"{Version?.Major}.{Version?.Minor}";
    }

    public static string AppendVersionString(this string text)
    {
        return text + " V." + GetVersionString();
    }

    public static Version Version => System.Reflection.Assembly.GetExecutingAssembly()?.GetName()?.Version;

    public static T DataBinding<T, TData>(this T t, TData dataSource, string propertyName, string dataMember) where T : IBindableComponent
    {
        var binding = new Binding(propertyName, dataSource, dataMember, false, DataSourceUpdateMode.OnPropertyChanged);
        t.DataBindings.Cast<Binding>().ToList().FindAll(it => it.PropertyName == propertyName).ForEach(t.DataBindings.Remove);
        t.DataBindings.Add(binding);
        return t;
    }
    public static T DataBinding<T, TData>(this T t, TData dataSource, Expression<Func<T, TData, bool>> exception) where T : IBindableComponent
    {
        var body = exception.Body as BinaryExpression;

        //区分左右 避免 参数写成 b.xxx==a.xxx 无法识别
        var p = exception.Parameters;
        var left = body?.Left as MemberExpression;
        var right = body?.Right as MemberExpression;

        var tp = left?.Expression == p[0] ? left : right;
        var tdatap = left?.Expression != p[0] ? left : right;

        var propertyName = tp?.Member.Name;
        var dataMember = tdatap?.Member.Name;
        if (propertyName == null || dataMember == null)
            throw new Exception("参数获取错误");

        return t.DataBinding(dataSource, propertyName, dataMember);
    }


    public static string ReplaceVariables(this string template, object data)
    {
        string result = template;
        var properties = data.GetType().GetProperties();
        foreach (var prop in properties)
        {
            //NET4.0 没有此方法 只能重写 不区分大小写方法
            //result = result.Replace($"{{{{{prop.Name}}}}}", prop.GetValue(data)?.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
            result = result.ReplaceIgnoreCase($"{{{{{prop.Name}}}}}", prop.GetValue(data)?.ToString() ?? "");
        }
        return result;
    }

    static string ReplaceIgnoreCase(this string original, string oldValue, string newValue)
    {
        string result = original;
        int index = original.IndexOf(oldValue, StringComparison.OrdinalIgnoreCase);

        while (index >= 0)
        {
            result = result.Remove(index, oldValue.Length).Insert(index, newValue);
            index = result.IndexOf(oldValue, index + newValue.Length, StringComparison.OrdinalIgnoreCase);
        }

        return result;
    }
}
